<script>
import UserApi from "@/api/user";
import util from "@/api/util";
import { ElNotification } from "element-plus";
export default {
  data() {
    return {
      username: "",
      password: "",
      confirmpwd: "",
      email: "",
    };
  },
  methods: {
    async register() {
      console.log(`用户名：${this.username}`);
      console.log(`密码：${this.password}`);
      console.log(`确认密码：${this.confirmpwd}`);
      console.log(`邮箱：${this.email}`);
      try {
        let api = new UserApi();
        let data = { username: this.username, password: this.password, email: this.email };
        let result = await api.register(data);
        let info = result.data;
        console.log("注册成功");
        console.log(info);
        if (info.code === 201) {
          ElNotification({
            title: "Success",
            message: info.msg,
            type: "success",
          });
          this.$router.replace("/login");
        }
      } catch (error) {
        let data = util.jsonTransfer(error);
        console.log(data.response.data);
        ElNotification({
          title: "Error",
          message: data.response.data.msg,
          type: "error",
        });
      }
    },
  },
};
</script>

<template>
  <div class="register">
    <h2>用户注册</h2>
    <div>
      <label for="username">用户名</label>
      <input type="text" id="username" placeholder="请输入用户名" v-model="username" />
      <span class="text-danger" v-if="this.username.length === 0">*</span>
    </div>
    <div>
      <label for="password">密码</label>
      <input type="password" id="password" placeholder="请输入密码" v-model="password" />
      <span class="text-danger" v-if="this.password.length === 0">*</span>
    </div>
    <div>
      <label for="password">确认密码</label>
      <input type="password" id="password" placeholder="请重复输入密码" v-model="confirmpwd" />
      <span class="text-danger" v-if="this.confirmpwd.length === 0">*</span>
      <span
        class="text-danger"
        v-if="this.confirmpwd.length > 0 && this.confirmpwd !== this.password"
        >密码不一致，请重新输入</span
      >
    </div>
    <div>
      <label for="email">邮箱</label>
      <input type="text" id="email" placeholder="请输入邮箱地址" v-model="email" />
      <span class="text-danger" v-if="this.email.length === 0">*</span>
    </div>
    <el-button type="primary" @click="register" plain>注册</el-button>
  </div>
</template>

<style scoped>
.text-danger {
  position: absolute;
  color: red;
}

.register {
  margin: 50px auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.register div {
  margin-top: 1rem;
}

.register label {
  display: inline-block;
  width: 80px;
  text-align-last: justify;
  padding: 0 10px;
}

button {
  margin-top: 25px;
}
</style>
